package com.cat.slidingWindow;

import java.util.HashMap;

/**
 * @author cat
 * @description https://leetcode.cn/problems/minimum-size-subarray-in-infinite-array/
 * @create 2025/7/30 16:50
 * @since JDK17
 */

public class Solution14 {
    static HashMap<Long, Integer> map = new HashMap<>();
    public int minSizeSubarray(int[] nums, int tar) {
        map.clear();
        int ans = 0, help = -1, n = nums.length, t = n;
        long sum = 0, target = tar;
        int[] ts = new int[n + n];
        map.put(0L, 0);
        for (int i = 0; i < n; i++) {
            sum += nums[i];
            map.put(sum, i + 1);
        }
        ans = (int)(target / sum * (long)n); // 多少个整体的数组
        target = sum - target % sum;  // 余下的数字
        sum = 0;
        for (int i = 0; i < n; i++) {
            ts[i] = ts[n + i] = nums[i];
        }
        nums = ts;
        n = n + n - 1;
        for (int l = 0, r = 0; r < n; r++) {
            sum += nums[r];
            while (l < n && sum > target) {
                sum -= nums[l++];   // 吐出窗口
            }
            if (target == sum) {
                help = Math.max(help, r - l + 1);
            }
        }
        return help == -1 ? -1 : t - help + ans;
    }
}
